<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init'];
    protected $noNeedRight = '*';

    /**
     * 加載初始化
     *
     * @param string $version 版本號
     * @param string $lng     經度
     * @param string $lat     緯度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服務端中轉模式需要修改為中轉
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //臨時修改上傳模式為服務端中轉
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上傳信息配置後
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上傳文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必須設定cdnurl為空,否則cdnurl函數計算錯誤
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合並分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //刪除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上傳分片文件
                //默認普通上傳文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默認普通上傳文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /*
    *單圖上傳
    */
    public function uploadPic()
    {

        $size = input('size',10);
        $size_buf = 1024*1024;
        $size = $size * $size_buf;

        $pic = request()->file('image');
        if ( !$pic ) {
            $this->error('請上傳文件');
        }
        $save_path = 'public/uploads/file/';

        $path = "/".$save_path.date('Y').'/'.date('m-d').'/';
        $root_path = ROOT_PATH.$path;
        if(!file_exists($root_path))
        {
            @mkdir($root_path, 0777, true);
        }
        $validate = ['size'=>$size];
        $ext="jpg,png,gif,jpeg";
        if ( $ext != '*' ) {
            $validate['ext'] = $ext;
        }
        $pic_info = $pic->validate($validate)->move($root_path );
        if($pic_info){
            $img_path = $path.$pic_info->getSaveName();
            $data['code'] = 200;
            $data['msg'] = '成功';
            $data['data'] = $img_path;
        }else{
            $data['code'] = 201;
            $data['msg'] = '圖片'.'上傳失敗,'.$pic->getError();
            $data['data'] = [];
        }

        if ( $data['code'] == 201 ) {
            $this->error($data['msg']);
        }
        $data_buf = [];
        $data_buf['pic']  = str_replace("/public","",$data['data']);
        $this->success('上傳成功',$data_buf);
    }


    /*
    *視頻上傳
    */
    public function uploadFile()
    {

        $size = input('size',10);
        $size_buf = 1024*1024;
        $size = $size * $size_buf;

        $pic = request()->file('video');
        if ( !$pic ) {
            $this->error('請上傳文件');
        }
        $save_path = 'public/uploads/file/';

        $path = "/".$save_path.date('Y').'/'.date('m-d').'/';
        $root_path = ROOT_PATH.$path;
        if(!file_exists($root_path))
        {
            @mkdir($root_path, 0777, true);
        }
        $validate = ['size'=>$size];
        $ext="avi,rmvb,wma,mp4,3gp,mov,mkv";
        if ( $ext != '*' ) {
            $validate['ext'] = $ext;
        }
        $pic_info = $pic->validate($validate)->move($root_path );
        if($pic_info){
            $img_path = $path.$pic_info->getSaveName();
            $data['code'] = 200;
            $data['msg'] = '成功';
            $data['data'] = $img_path;
        }else{
            $data['code'] = 201;
            $data['msg'] = '視頻'.'上傳失敗,'.$pic->getError();
            $data['data'] = [];
        }

        if ( $data['code'] == 201 ) {
            $this->error($data['msg']);
        }
        $data_buf = [];
        $data_buf['pic']  = str_replace("/public","",$data['data']);
        $this->success('上傳成功',$data_buf);
    }

    /*
    *多圖上傳
    */
    public function uploadPics()
    {

        // 获取表单上传文件
        $files = request()->file('image');
        if ( !$files ) {
            $this->error('請上傳圖片');
        }
        if ( !is_array($files) ) {
            $this->error('請上傳多張圖片');
        }
        $size = input('size',10);
        $size_buf = 1024*1024;
        $size = $size * $size_buf;

        $save_path = 'public/uploads/file/';

        $path = "/".$save_path.date('Y').'/'.date('m-d').'/';
        $root_path = ROOT_PATH.$path;
        if(!file_exists($root_path))
        {
            @mkdir($root_path, 0777, true);
        }

        $validate = ['size'=>$size];

        $ext="jpg,png,gif,jpeg";
        if ( $ext != '*' ) {
            $validate['ext'] = $ext;
        }

        $data['code'] = 200;
        $data['msg'] = '成功';
        $images = [];

        $all_status = 1;
        foreach($files as $file){
            $pic_info = $file->validate($validate)->move($root_path );
            if($pic_info){
                $img_path = $path.$pic_info->getSaveName();
                $data['code'] = 200;
                $data['msg'] = '成功';
                $images[] = $img_path;
            }else{
                $data['code'] = 201;
                $data['msg'][] = '圖片'.'上傳失敗,'.$file->getError();
                $all_status = 0;
            }
        }
        if ( !$images ) {
            $this->error('上傳失敗');
        }
        $msg = '上傳成功';

        if ( !$all_status ) {
            $msg = '有部分圖片上傳失敗';
        }

        foreach ($images as $key => &$value) {
            $value = str_replace("/public","",$value);
        }
        unset($value);
        $this->success($msg,$images);
    }
}
